package iot.plugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.BrokerPlugin;
import org.apache.activemq.broker.ProducerBrokerExchange;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.Message;

public class IpPlugin implements BrokerPlugin {
    static class IpBindFilter extends BrokerFilter {

        public IpBindFilter(Broker next) {
            super(next);
        }

        @Override
        public void send(ProducerBrokerExchange producerExchange, Message messageSend) throws Exception {
            if(!(messageSend instanceof ActiveMQTextMessage)){
                throw new RuntimeException("not allow,must be json string message");
            }
            String remoteAddr = producerExchange.getConnectionContext().getConnection().getRemoteAddress();//tcp://127.0.0.1:61468
            String ip = remoteAddr.substring(6,remoteAddr.lastIndexOf(':'));
            ActiveMQTextMessage textMessage = (ActiveMQTextMessage) messageSend;
            String content = textMessage.getText();
            JSONObject jsonObj = JSON.parseObject(content);
            jsonObj.put("producerIp",ip);
            textMessage.setText(jsonObj.toJSONString());
            super.send(producerExchange, textMessage);
        }
    }
    public Broker installPlugin(Broker broker) throws Exception {
        return new IpBindFilter(broker);
    }
}
